const express = require("express");
const Result = require("../../models/Result");
const { decoded } = require("../../utils/index");
const { PRIVATE_KEY, JWT_EXPIRED } = require("../../utils/constant");
const {
  getClassList,
  editClass,
  createClass,
  deleteClass,
  getTotalCount,
  getClassInfoById,
  getClassSchedule,
  editClassSchedule,
  createClassSchedule,
  deleteClassSchedule,
  getMyClassList,
  createExam,
  editExam,
} = require("../../services/class");
const {
  getUserInfoById,
  getUserListByNameOrCardId,
} = require("../../services/user");

const jwt = require("jsonwebtoken");
const jwtAuth = require("../jwt");
// 注册路由
const router = express.Router();
router.use(jwtAuth);

//获取课程列表接口
router.get("/list", async (req, res, next) => {
  try {
    let userList = [];
    if (req.query.teacherInfo && req.query.teacherInfo.trim() !== "") {
      const data = await getUserListByNameOrCardId(req.query.teacherInfo);
      if (data.length === 0) {
        userList.push(0);
      } else {
        for (let i = 0; i < data.length; i++) {
          userList.push(data[i].id);
        }
      }
    }
    const data = await getClassList(req.query, userList);
    for (let j = 0; j < data.length; j++) {
      data[j].teacherList = JSON.parse(data[j].teacherList);
      for (let i = 0; i < data[j].teacherList.length; i++) {
        const userId = data[j].teacherList[i];
        const userInfo = await getUserInfoById(userId);
        data[j].teacherList[i] = {
          label: userInfo.userName,
          value: userInfo.id,
        };
      }
    }
    const total = await getTotalCount(req.query, userList);
    new Result(
      {
        list: data,
        page: {
          pageNum: req.query.pageNum,
          pageSize: req.query.pageSize,
          total: total.totalCount,
        },
      },
      "课程列表查询成功"
    ).success(res);
  } catch (err) {
    console.log(err);
    new Result("课程信息查询失败").fail(res);
  }
});

router.get("/getMyClassList", async (req, res, next) => {
  const data = await getMyClassList(1);
  for (let j = 0; j < data.length; j++) {
    if (data[j].invigilatorId) {
      data[j].invigilatorName = (
        await getUserInfoById(data[j].invigilatorId)
      ).userName;
    } else {
      data[j].invigilatorName = "";
    }

    data[j].teacherList = JSON.parse(data[j].teacherList);
    for (let i = 0; i < data[j].teacherList.length; i++) {
      const userId = data[j].teacherList[i];
      const userInfo = await getUserInfoById(userId);
      data[j].teacherList[i] = {
        label: userInfo.userName,
        value: userInfo.id,
      };
    }
    if (data[j].deputyInvigilatorArr) {
      data[j].deputyInvigilatorArr = JSON.parse(data[j].deputyInvigilatorArr);
      for (let i = 0; i < data[j].deputyInvigilatorArr.length; i++) {
        const userId = data[j].deputyInvigilatorArr[i];
        const userInfo = await getUserInfoById(userId);
        data[j].deputyInvigilatorArr[i] = {
          label: userInfo.userName,
          value: userInfo.id,
        };
      }
    }
    if (data[j].linkStudentId) {
      data[j].linkStudentId = JSON.parse(data[j].linkStudentId);
      for (let i = 0; i < data[j].linkStudentId.length; i++) {
        const userId = data[j].linkStudentId[i];
        const userInfo = await getUserInfoById(userId);
        data[j].linkStudentId[i] = {
          label: userInfo.userName,
          value: userInfo.id,
        };
      }
      console.log("所有学生", data[j].linkStudentId);
    }
  }
  new Result(data, "课程列表查询成功").success(res);
});

router.get("/getClassInfoById", async (req, res, next) => {
  try {
    const data = await getClassInfoById({ id: req.query.id });
    if (!data) {
      new Result("课程信息查询失败").fail(res);
    } else {
      data.teacherList = JSON.parse(data.teacherList);
      for (let i = 0; i < data.teacherList.length; i++) {
        const userId = data.teacherList[i];
        const userInfo = await getUserInfoById(userId);
        data.teacherList[i] = {
          label: userInfo.userName,
          value: userInfo.id,
        };
      }
      new Result(data, "课程信息查询成功").success(res);
    }
  } catch (err) {
    console.log(err);
    new Result("课程信息查询失败").fail(res);
  }
});

router.post("/editExamination", async (req, res, next) => {
  if (req.body.int) {
    // 修改
    const query = req.body;
    const int = query.int;
    delete query.int;
    editExam(req.body, int)
      .then((data) => {
        new Result("操作成功").success(res);
      })
      .catch((err) => {
        new Result("操作失败", err).fail(res);
      });
  } else {
    // 新增
    const query = req.body;
    delete query.int;
    createExam(req.body)
      .then((data) => {
        new Result("操作成功").success(res);
      })
      .catch((err) => {
        console.log(err);
        new Result("操作失败", err).fail(res);
      });
  }
});

//编辑课程接口
router.post("/edit", function (req, res, next) {
  editClass(req.body)
    .then((data) => {
      new Result("操作成功").success(res);
    })
    .catch((err) => {
      new Result("操作失败").fail(res);
    });
});

//创建课程接口
router.post("/create", function (req, res, next) {
  createClass(req.body, decoded(req).cardId)
    .then((data) => {
      new Result("操作成功").success(res);
    })
    .catch((err) => {
      console.log(err);
      new Result("操作失败").fail(res);
    });
});

//删除课程接口
router.post("/delete", function (req, res, next) {
  deleteClass(req.body)
    .then((data) => {
      new Result("操作成功").success(res);
    })
    .catch((err) => {
      new Result("操作失败").fail(res);
    });
});

router.get("/getClassSchedule", async (req, res, next) => {
  const linkClassId = req.query.linkClassId;
  getClassSchedule(linkClassId)
    .then((data) => {
      data.forEach((item) => {
        item.weekNumArr = JSON.parse(item.weekNumArr);
      });
      new Result(data, "查询成功").success(res);
    })
    .catch((err) => {
      console.log(err);
      new Result("查询失败").fail(res);
    });
});

//编辑排课安排接口
router.post("/editClassSchedule", function (req, res, next) {
  const reqBody = req.body;
  reqBody.weekNumArr = JSON.stringify(reqBody.weekNumArr);
  editClassSchedule(reqBody)
    .then((data) => {
      new Result("操作成功").success(res);
    })
    .catch((err) => {
      new Result("操作失败").fail(res);
    });
});

//创建排课安排接口
router.post("/createClassSchedule", function (req, res, next) {
  const reqBody = req.body;
  reqBody.weekNumArr = JSON.stringify(reqBody.weekNumArr);
  createClassSchedule(reqBody)
    .then((data) => {
      new Result("操作成功").success(res);
    })
    .catch((err) => {
      console.log(err);
      new Result("操作失败").fail(res);
    });
});

//删除排课安排接口
router.post("/deleteClassSchedule", function (req, res, next) {
  deleteClassSchedule(req.body)
    .then((data) => {
      new Result("操作成功").success(res);
    })
    .catch((err) => {
      new Result("操作失败").fail(res);
    });
});

module.exports = router;
